package com.example.lcode.list;

public class Question2 {

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null;
        ListNode currentNode = null;
        int num = 0;
        while (l1 != null || l2 != null) {
            int value =  (l2 != null ? l2.val : 0)  +  (l1 != null ? l1.val : 0) + num;
            if (value >= 10) {
                value = value - 10;
                num = 1;
            } else {
                num = 0;
            }
            ListNode listNode = new ListNode(value);
            if (head == null) {
                head = listNode;
            }
            if (currentNode == null) {
                currentNode = listNode;
            } else {
                currentNode.next = listNode;
                currentNode = listNode;
            }
            l1 = l1 != null ? l1.next : null;
            l2 = l2 != null ? l2.next : null;
        }
        if (num == 1) {
            currentNode.next = new ListNode(1);
        }
        return head;
    }

    public static void main(String[] args) {

    }

}
